<template>
  <div>
    <a-radio-group :value="takeClassType" style="margin-bottom:15px;" @change="changeTakeClassType">
      <a-radio-button :value="1">已上课记录</a-radio-button>
      <a-radio-button :value="2">待上课记录</a-radio-button>
    </a-radio-group>
    <div class="already" v-if="takeClassType==1">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="上课日期">
                <a-range-picker @change="onChange" v-model="date" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="所在班级">
                <a-select
                  v-model="queryParam.class_id"
                  allowClear
                  style="width:340px;"
                  placeholder="请选择所在班级"
                >
                  <a-select-option
                    v-for="(item,index) in class_"
                    :key="index"
                    :value="item.id"
                  >{{item.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="上课老师">
                <a-select
                  v-model="queryParam.teacher_id"
                  allowClear
                  style="width:340px;"
                  placeholder="请选择上课老师"
                >
                  <a-select-option
                    v-for="(item,index) in teacher"
                    :key="index"
                    :value="item.id"
                  >{{item.name}}</a-select-option>
                </a-select>
              </a-form-item>
              <a style="cursor:pointer" v-if="advanced" @click="more" id="moreButton">
                收起
                <a-icon type="up"></a-icon>
              </a>
              <a style="cursor:pointer" v-if="!advanced" @click="more" id="moreButton">
                展开
                <a-icon type="down"></a-icon>
              </a>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="报读课程">
                  <a-select
                    v-model="queryParam.course_id"
                    allowClear
                    style="width:340px;"
                    placeholder="请选择报读课程"
                  >
                    <a-select-option
                      v-for="(item,index) in course"
                      :key="index"
                      :value="item.id"
                    >{{item.name}}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
          </a-row>
        </a-form>
      </div>
      <a-button style="margin-bottom:10px;" @click="excelOut">导出</a-button>
      <!-- <div class="alert">
        <span class="ele">
          到课
          <span class="bigger"></span>次
        </span>
        <span class="ele">
          迟到
          <span class="bigger"></span>次
        </span>
        <span class="ele">
          请假
          <span class="bigger"></span>次
        </span>
        <span class="ele">
          未到
          <span class="bigger"></span>次
        </span>
      </div>-->
      <s-table
        ref="table_already"
        size="default"
        rowKey="key"
        :columns="columns_already"
        :data="loadDataAlready"
        showPagination="auto"
        class="user_management_table"
      >
        <span slot="created_at" slot-scope="text,record">{{record.created_at|formatDate}}</span>
        <span slot="teachers" slot-scope="text,record">
          <span v-for="(item,index) in record.teachers" :key="index">
            <span>{{item}}</span>
            <span v-if="index<record.teachers.length-1">，</span>
          </span>
        </span>
        <span slot="course" slot-scope="text,record">
          <span v-if="record.course&&record.course.name">
            <span :title="record.course.name">{{record.course.name}}</span>
          </span>
          <span v-else>--</span>
        </span>
        <span
          slot="type"
          slot-scope="text,record"
        >{{record.type==1?'到课':record.type==2?'迟到':record.type==3?'请假':record.type==4?'未到':''}}</span>
        <span slot="deduction" slot-scope="text,record">
          <span v-if="record.super_status&&record.super_status==3">
            <span v-if="record.go_beyond">
              {{Number(record.go_beyond)+Number(record.deduction)}}
            </span>
            <span v-else>{{Number(record.deduction)}}</span>
          </span>
          <span v-else-if="record.consume_type==1">{{record.deduction}}</span>
          <span v-else-if="record.consume_type==2">按天自动消耗</span>
          <span v-if="record.super_status">
            <!-- 超上 不需要扣 -->
            <span v-if="record.super_status==2">(超上{{record.go_beyond}}课时，无需不扣)</span>
            <!-- 超上  需要扣 -->
            <span v-else-if="record.super_status==1">
              <!-- <span v-if="record.consume_type==1">
                (超上{{record.go_beyond}}课时，
                <a>立即处理</a> )
              </span>
              <span v-else-if="record.consume_type==2">
                (本次超上，
                <a>不再提醒</a>)
              </span>-->
              (超上{{record.go_beyond}}课时，
              <a-popconfirm
                title="请选择要执行的操作"
                overlayClassName="studentInfo_followUpDel"
                ok-text="补扣课时"
                @confirm="sureBukou(record)"
                cancel-text="无需补扣"
                @cancel="cancelBukou(record)"
              >
                <a>立即处理</a>
              </a-popconfirm>)
            </span>
            <span v-else-if="record.super_status==3"></span>   
            <span v-else-if="record.super_status==4">
              (本次超上，
              <a-popconfirm
                title="确定后，将不再对本次超上进行提醒"
                overlayClassName="studentInfo_followUpDel"
                ok-text="确定"
                @confirm="sureWarning(record)"
                cancel-text="取消"
              >
                <a>不再提醒</a>
              </a-popconfirm>)
            </span>
            <!-- <span v-else-if="record.super_status==5">
              (本次超上)
            </span>-->
          </span>
        </span>
      </s-table>
    </div>
    <div class="notYet" v-if="takeClassType ==2">
      <div class="top">
        <div class="title">
          <span>一周课表</span>
          <span class="dateArea">{{monday}}~{{sunday}}</span>
        </div>
        <div class="buttons">
          <a-button @click="getNewWeek(monday,sunday,-7)">上周</a-button>
          <a-button @click="getNowWeek(nowMonday,nowSunday)">本周</a-button>
          <a-button @click="getNewWeek(monday,sunday,7)">下周</a-button>
        </div>
      </div>
      <a-table
        :data-source="loadDataNotYet"
        :loading="loading"
        :columns="columns_notYet"
        :pagination="false"
        class="user_management_table"
        style="margin-top:10px;border: 1px solid #e8e8e8"
      >
        <span slot="attend_class_day" slot-scope="text,record">
          <span>
            {{record.attend_class_day|dayjs}}
            <span
              v-if="record.class_start_time&&record.class_end_time"
            >{{record.class_start_time}}~{{record.class_end_time}}</span>
          </span>
        </span>
      </a-table>
    </div>
  </div>
</template>

<script>
import { classList } from '@/api/class'
import { teacherList } from '@/api/teacher'
import { coursesList } from '@/api/courseCharge'
import { STable, Ellipsis } from '@/components'
import {
  takeClassAlready,
  takeClassNotYet,
  takeClassExcel,
  noMakeUp,
  makeUp,
  noRemind,
  isAdequate,
} from '@/api/student'
export default {
  name: 'takeClass',
  props: ['studentId'],
  components: { STable, Ellipsis },
  created() {
    classList({
      pageSize: 999999999,
      school_id: this.$store.state.user.school,
    }).then((res) => {
      this.class_ = res.data
    })
    teacherList({
      pageSize: 99999999,
      school_id: this.$store.state.user.school,
    }).then((res) => {
      this.teacher = res.data
    })
    coursesList({
      pageSize: 99999999,
      school_id: this.$store.state.user.school,
    }).then((res) => {
      this.course = res.data
    }),
      this.getMonday_Sunday()
    this.reloadTable()
  },
  data() {
    return {
      date: null,
      takeClassType: 1,
      class_: [],
      course: [],
      teacher: [],
      queryParam: {
        start_time: undefined,
        end_time: undefined,
        teacher_id: undefined,
        class_id: undefined,
        course_id: undefined,
        student_id: Number(this.studentId),
        school_id: this.$store.state.user.school,
      },
      advanced: false,
      columns_already: [
        {
          title: '点名时间',
          dataIndex: 'created_at',
          width: 150,
          align: 'center',
          ellipsis: true,
          scopedSlots: { customRender: 'created_at' },
        },
        {
          title: '班级名称',
          dataIndex: 'class_name',
          width: 150,
          ellipsis: true,
          align: 'center',
        },
        {
          title: '消耗课程',
          dataIndex: 'course',
          width: 150,
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'course' },
        },
        {
          title: '上课时间',
          dataIndex: 'attend_class_day',
          ellipsis: true,
          align: 'center',
        },
        {
          title: '上课老师',
          dataIndex: 'teachers',
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'teachers' },
        },
        {
          title: '到课状态',
          dataIndex: 'type',
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'type' },
        },
        {
          title: '扣课时',
          dataIndex: 'deduction',
          ellipsis: true,
          width: 300,
          scopedSlots: { customRender: 'deduction' },
        },
        {
          title: '课消金额',
          dataIndex: 'sum_class_consume',
          align: 'center',
          customRender(text) {
            return text>=0 ? '￥' + text:'--'
          },
        },

        {
          title: '备注',
          width: '150px',
          ellipsis: true,
          dataIndex: 'remarks',
          fixed: 'right',
          customRender(text) {
            return text || '-'
          },
        },
      ],
      loadDataAlready: (parameter) => {
        return takeClassAlready(Object.assign(parameter, this.queryParam, {}))
          .then((res) => {
            console.log(res, 'ressss')
            return res
          })
          .catch((err) => {
            this.$message.error(err.data.message || '查询失败')
          })
      },
      loading: false,
      loadDataNotYet: [],
      columns_notYet: [
        {
          title: '班级名称',
          dataIndex: 'class_name',
          width: 150,
          ellipsis: true,
          align: 'center',
        },
        {
          title: '上课时间',
          dataIndex: 'attend_class_day',
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'attend_class_day' },
        },
        {
          title: '上课教室',
          dataIndex: 'class_room_name',
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'class_room_name' },
        },
        {
          title: '上课老师',
          dataIndex: 'teachers',
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'teachers' },
        },
        {
          title: '上课内容',
          dataIndex: 'content',
          ellipsis: true,
          align: 'center',
          scopedSlots: { customRender: 'content' },
        },

        // {
        //   title: '操作',
        //   width: '150px',
        //   ellipsis: true,
        //   dataIndex: 'action',
        //   fixed: 'right',
        //   scopedSlots: { customRender: 'action' }
        // }
      ],
      monday: '',
      sunday: '',
      nowMonday: '',
      nowSunday: '',
    }
  },
  methods: {
    // 补扣课时
    sureBukou(record) {
      let that = this
      isAdequate(record.id)
        .then((res) => {
          if (res.status == 1) {
            that.$confirm({
              title: '补扣超上课时',
              content: `学员课时充足，将补扣超上的${res.info.go_beyond}课时，课消金额为￥${res.info.consume_amount}，补扣后此课程还剩${res.info.surplus_hour}课时。`,
              onOk() {
                makeUp(record.id)
                  .then((res) => {
                    that.$refs.table_already.refresh(true)
                    that.$message.success('操作成功')
                  })
                  .catch((err) => {
                    that.$message.error(err.data.message || '操作失败')
                  })
              },
              onCancel() {
                console.log('Cancel')
              },
            })
          } else {
            this.$warning({
              title: '补扣超上课时',
              content: '剩余课时不足，请先为学员续报 课程名称 后再进行补扣。',
            })
          }
        })
        .catch((err) => {
          that.$message.error(err.data.message || '操作失败')
        })
    },
    //无需补扣
    cancelBukou(record) {
      let that = this
      this.$confirm({
        title: '操作确认',
        content: '确定后，此条记录无法再进行补扣',
        onOk() {
          noMakeUp(record.id)
            .then((res) => {
              that.$refs.table_already.refresh(true)
              that.$message.success('操作成功')
            })
            .catch((err) => {
              that.$message.error(err.data.message || '操作失败')
            })
        },
        onCancel() {},
      })
    },
    //确认不再提醒
    sureWarning(record) {
      // let that=this
      noRemind(record.id)
        .then((res) => {
          this.$refs.table_already.refresh(true)
          this.$message.success('操作成功')
        })
        .catch((err) => {
          that.$message.error(err.data.message || '操作失败')
        })
      // this.$confirm({
      //   title: 'Are you sure delete this task?',
      //   content: 'Some descriptions',
      //   onOk() {

      //   },
      //   onCancel() {
      //     console.log('Cancel');
      //   },
      // });
    },
    more() {
      this.advanced = !this.advanced
    },
    onChange(date, dateArr) {
      this.queryParam.start_time = dateArr[0]
      this.queryParam.end_time = dateArr[1]
    },
    changeTakeClassType(e) {
      this.takeClassType = e.target.value
    },
    getMonday_Sunday(e) {
      let now
      if (e) {
        now = new Date(e)
      } else {
        now = new Date()
      }
      let nowTime = now.getTime()
      let day = now.getDay()
      let oneDayTime = 24 * 60 * 60 * 1000
      let MondayTime = nowTime - (day - 1) * oneDayTime //显示周一
      let SundayTime = nowTime + (7 - day) * oneDayTime //显示周日
      if (e) {
        this.monday = this.formatDate(new Date(MondayTime))
        this.sunday = this.formatDate(new Date(SundayTime))
      } else {
        this.monday = this.formatDate(new Date(MondayTime))
        this.nowMonday = this.formatDate(new Date(MondayTime))
        this.nowSunday = this.formatDate(new Date(SundayTime))
        this.sunday = this.formatDate(new Date(SundayTime))
      }
    },
    formatDate(date) {
      let myyear = date.getFullYear()
      let mymonth = date.getMonth() + 1
      let myweekday = date.getDate()
      if (mymonth < 10) {
        mymonth = '0' + mymonth
      }
      if (myweekday < 10) {
        myweekday = '0' + myweekday
      }
      return myyear + '-' + mymonth + '-' + myweekday
    },
    getNewWeek(e, data, num) {
      let monday1 = new Date(e)
      let sunday1 = new Date(data)
      let monday2 = new Date(monday1)
      let sunday2 = new Date(sunday1)
      monday2.setDate(monday1.getDate() + num)
      sunday2.setDate(sunday1.getDate() + num)
      let timeMonday = monday2.getFullYear() + '-' + (monday2.getMonth() + 1) + '-' + monday2.getDate()
      let timeSunday = sunday2.getFullYear() + '-' + (sunday2.getMonth() + 1) + '-' + sunday2.getDate()
      this.monday = timeMonday
      this.sunday = timeSunday
    },
    getNowWeek(e, sun) {
      this.monday = e
      this.sunday = sun
    },
    reloadTable() {
      this.loading = true
      takeClassNotYet({
        pageSize: 999999999,
        student_id: this.studentId,
        date: this.monday,
      })
        .then((res) => {
          this.loading = false
          this.loadDataNotYet = res.data
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取待上课记录失败')
        })
    },
    excelOut() {
      takeClassExcel(this.queryParam)
        .then((res) => {
          let url = res.url.url + res.url.path
          window.location.href = url
        })
        .catch((err) => {
          this.$message.error(err.data.message || '获取导出资源失败~')
        })
    },
    // download(blobUrl) {
    //   const a = document.createElement('a')
    //   a.style.display = 'none'
    //   a.download = '上课记录'
    //   a.href = blobUrl
    //   a.click()
    //   document.body.removeChild(a)
    // }
  },
  watch: {
    monday(val) {
      this.reloadTable()
    },
    queryParam: {
      handler() {
        this.$refs.table_already.refresh(true)
      },
      deep: true,
    },
  },
}
</script>
<style lang="less">
.studentInfo_followUpDel {
  .ant-popover-content {
    .ant-popover-inner {
      padding: 10px !important;
    }
  }
}
</style>
<style lang="less" scoped>
.already {
  .alert {
    margin: 10px 0;
    background: #e6f7ff;
    padding: 0px 15px;
    color: #000;
    border: 1px solid #91d5ff;
    line-height: 32px;
    border-radius: 4px;
    .ele {
      margin-right: 10px;
      .bigger {
        color: rgb(51, 51, 51);
        font-weight: 500;
      }
    }
  }
}
.notYet {
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .buttons {
      button {
        margin-left: 10px;
      }
    }
  }
}
#moreButton {
  position: absolute;
  top: 5px;
  right: 34px;
}
</style>